<template>
  <el-dialog
    v-model="visible"
    title="软件授权"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="auth-dialog">
      <div class="machine-info">
        <h4>当前机器码：</h4>
        <el-input
          v-model="machineId"
          type="textarea"
          :rows="3"
          readonly
          placeholder="正在获取机器码..."
        />
        <p class="tips">请将此机器码提供给软件供应商获取授权文件</p>
      </div>

      <div class="license-input">
        <h4>授权文件内容：</h4>
        <el-input
          v-model="licenseKey"
          type="textarea"
          :rows="4"
          placeholder="请粘贴授权文件内容"
          :class="{ 'is-error': licenseError }"
        />
        <p v-if="licenseError" class="error-text">{{ licenseError }}</p>
      </div>

      <div class="dialog-footer">
        <el-button type="primary" @click="handleActivate" :loading="activating">
          确认授权
        </el-button>
        <el-button @click="handleCancel">退出软件</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getMachineId, activateLicense } from '@/utils/auth'

const visible = ref(true)
const machineId = ref('')
const licenseKey = ref('')
const licenseError = ref('')
const activating = ref(false)

const emit = defineEmits(['activated', 'cancel'])

onMounted(async () => {
  try {
    machineId.value = await getMachineId()
  } catch (error) {
    console.error('获取机器码失败:', error)
    machineId.value = '获取机器码失败'
  }
})

const handleActivate = async () => {
  if (!licenseKey.value.trim()) {
    licenseError.value = '请输入授权文件内容'
    return
  }

  activating.value = true
  licenseError.value = ''

  try {
    const success = await activateLicense(licenseKey.value.trim())
    if (success) {
      ElMessage.success('授权成功！')
      emit('activated')
      visible.value = false
    } else {
      licenseError.value = '授权失败，请检查授权文件是否正确'
    }
  } catch (error) {
    console.error('激活授权失败:', error)
    licenseError.value = '授权激活失败，请重试'
  } finally {
    activating.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}
</script>

<style scoped>
.auth-dialog {
  padding: 10px 0;
}

.machine-info,
.license-input {
  margin-bottom: 20px;
}

.machine-info h4,
.license-input h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #606266;
}

.tips {
  margin: 8px 0 0 0;
  font-size: 12px;
  color: #909399;
}

.error-text {
  margin: 8px 0 0 0;
  font-size: 12px;
  color: #f56c6c;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.is-error :deep(.el-textarea__inner) {
  border-color: #f56c6c;
}
</style>